package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class WmUserServiceImpl extends BaseServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    @Override
    public ResponseResult login(WmUserDto wmUserDto) {
        if (StringUtils.isEmpty(wmUserDto.getName()) ||
                StringUtils.isEmpty(wmUserDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名和密码不能为空");
        }
        //根据姓名查看用户是否存在
        WmUser one = getOne(new LambdaQueryWrapper<WmUser>().eq(WmUser::getName, wmUserDto.getName()));
        if (one == null)return userNotExist;
        String pw = DigestUtils.md5DigestAsHex((wmUserDto.getPassword() + one.getSalt()).getBytes());
        if (pw.equals(one.getPassword())){
            HashMap<String, Object> map = new HashMap<>();
            one.setPassword("");
            one.setSalt("");
            map.put("token", AppJwtUtil.getToken(one.getId().longValue()));
            map.put("user",one);
            return ResponseResult.okResult(map);
        }else return ResponseResult.okResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);


    }
}
